package com.carambatv.android.ui;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.LinearLayout;

import com.carambatv.android.R;
import com.carambatv.android.ui.sliding.MyApiHelper;
import com.carambatv.android.utils.YtubeProcessor;
import com.the111min.android.api.ResponseReceiver;

public final class ListScrollListener implements AbsListView.OnScrollListener, ResponseReceiver {

	private MyApiHelper apiHelper = null;
	private boolean isEnableToLoadind = true;
	private int sFirstItem = 1;
	private String type;
	private LinearLayout root;
	private View loadingView;
	private View mErrorView;
	private Button retryButton;
	public static final LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1);

	public ListScrollListener(Context context, String type, View root) {
		this.type = type;
		this.root = (LinearLayout) root;
		loadingView = LayoutInflater.from(context).inflate(R.layout.jamendo_footer_loading, null);
		mErrorView = LayoutInflater.from(context).inflate(R.layout.jamendo_footer_error, null);
		retryButton = (Button) mErrorView.findViewById(R.id.retry);
		retryButton.setOnClickListener(onClickListener);

		apiHelper = new MyApiHelper(context, this);
		apiHelper.getVideo(type, sFirstItem);
		this.root.addView(loadingView, lp);
	}

	final OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			apiHelper.getVideo(type, sFirstItem + MyApiHelper.COUNT);
			root.removeAllViews();
			root.addView(loadingView, lp);
		}
	};

	/**
	 * {@inheritDoc}
	 */
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		if (firstVisibleItem >= totalItemCount - visibleItemCount && isEnableToLoadind) {
			isEnableToLoadind = false;
			apiHelper.getVideo(type, sFirstItem + MyApiHelper.COUNT);
			if (root.getChildCount() == 0)
				this.root.addView(loadingView, lp);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void onScrollStateChanged(AbsListView view, int scrollState) {

	}

	@Override
	public void onRequestSuccess(int token, Bundle result) {
		root.removeAllViews();
		int count = result.getInt(YtubeProcessor.TOTAL_RESULTS);
		isEnableToLoadind = ((sFirstItem + MyApiHelper.COUNT) < count);
		if (isEnableToLoadind)
			sFirstItem += MyApiHelper.COUNT;
	}

	@Override
	public void onRequestFailure(int token, Bundle result) {
	}

	@Override
	public void onError(int token, Exception e) {
		root.removeAllViews();
		this.root.addView(mErrorView, lp);
	}
}
